package com.malty.mall.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.malty.mall.dao.ums.UmsResourceMapper;
import com.malty.mall.domain.dto.req.UmsResourceParam;
import com.malty.mall.domain.entity.ums.UmsResource;
import com.malty.mall.domain.entity.ums.UmsResourceType;
import com.malty.mall.domain.entity.ums.UmsRoleResourceRelation;
import com.malty.mall.service.ums.IUmsResourceService;
import com.malty.mall.service.ums.IUmsResourceTypeService;
import com.malty.mall.service.ums.IUmsRoleResourceService;
import com.malty.mall.util.PreconditionUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author malty
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UmsResourceServiceImpl extends ServiceImpl<UmsResourceMapper, UmsResource> implements IUmsResourceService {
    private final IUmsResourceTypeService resourceTypeService;
    private final IUmsRoleResourceService roleResourceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(UmsResourceParam resourceParam) {
        if (resourceParam.getPath() != null && resourceParam.getPath().startsWith("/")) {
            UmsResource umsResource = new UmsResource(resourceParam);
            UmsResourceType resourceType = resourceTypeService.getById(resourceParam.getTypeId());
            PreconditionUtils.check(resourceType == null, "资源类型不存在");
            boolean save = this.save(umsResource);
            PreconditionUtils.check(!save, "创建失败");
            return true;
        }
        throw new RuntimeException("资源路径需要以/开头");
    }

    @Override
    public List<UmsResourceParam> listByRole(Integer roleId) {
        List<UmsRoleResourceRelation> list = roleResourceService.list(Wrappers.<UmsRoleResourceRelation>lambdaQuery().eq(UmsRoleResourceRelation::getRoleId, roleId));
        List<Integer> resourceList = list.stream().map(UmsRoleResourceRelation::getResourceId).collect(Collectors.toList());
        List<UmsResource> resources = this.list(Wrappers.<UmsResource>lambdaQuery().in(UmsResource::getId, resourceList));
        return UmsResource.getParamBatch(resources);
    }

    @Override
    public List<UmsResourceParam> listAll() {
        List<UmsResource> resourceTypes = this.list();
        return UmsResource.getParamBatch(resourceTypes);
    }

    @Override
    public Boolean deleteResourceById(Integer id) {
        return this.remove(Wrappers.<UmsResource>lambdaQuery().eq(UmsResource::getTypeId, id));
    }
}
